#include "HttpConnect.h"

HttpConnect::HttpConnect() {}

HttpConnect::~HttpConnect() { close(sockfd); }

void HttpConnect::Init()
{
    struct sockaddr_in address;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    address.sin_port = htons(80);

    if (inet_pton(AF_INET, "127.0.0.1", &address.sin_addr) <= 0)
    {
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        return;
    }

    if (connect(sockfd, (struct sockaddr *)&address, sizeof(address)) < 0)
    {
        std::cerr << "Connection Failed" << std::endl;
        return;
    }
}

void HttpConnect::socketHttp(std::string request)
{
    write(sockfd, request.c_str(), request.size());
}

void HttpConnect::postData(std::string host, std::string path, std::string post_content)
{
    // POST请求方式
    std::stringstream stream;
    stream << "POST " << path;
    stream << " HTTP/1.0\r\n";
    stream << "Host: " << host << "\r\n";
    // stream << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN;
    // rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
    stream << "Content-Type:application/x-www-form-urlencoded\r\n";
    stream << "Content-Length:" << post_content.length() << "\r\n";
    stream << "Connection:keep-alive\r\n\r\n";
    stream << post_content.c_str();

    socketHttp(stream.str());
}

void HttpConnect::getData(std::string host, std::string path, std::string get_content)
{
    // GET请求方式
    std::stringstream stream;
    stream << "GET " << path << "?" << get_content;
    stream << " HTTP/1.0\r\n";
    stream << "Host: " << host << "\r\n";
    stream << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; "
              "rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
    stream << "Connection:keep-alive\r\n\r\n";

    socketHttp(stream.str());
}

void HttpConnect::keepConnect(std::string host, std::string path)
{
    // POST请求方式
    std::stringstream stream;
    stream << "GET " << path;
    stream << " HTTP/1.0\r\n";
    stream << "Host: " << host << "\r\n";
    stream << "Connection:keep-alive\r\n\r\n";

    socketHttp(stream.str());
}

void HttpConnect::closeConnect(std::string host, std::string path)
{
    // POST请求方式
    std::stringstream stream;
    stream << "GET " << path;
    stream << " HTTP/1.0\r\n";
    stream << "Host: " << host << "\r\n";
    stream << "Connection:close\r\n\r\n";

    socketHttp(stream.str());
}